// 用户预约数据
var datas = [
    {
        name: '小明',
        field: '1',
        startTime: '2018/1/1 13:01',
        endTime: '2018/1/1 14:59',
        style: {
            background: "red"
        },
        status: {
            text: "用户取消"
        },
        bespoke: "用户取消"
    },
    {
        name: '老明',
        field: '2',
        startTime: '2018/1/1 08:01',
        endTime: '2018/1/1 13:59',
        style: {
            background: "brown"
        },
        // status: {
        //     text: "故障待修复"
        // },
        bespoke: '场馆修复中'
    },
    {
        name: '小刚',
        field: '3',
        startTime: '2018/1/1 08:01',
        endTime: '2018/1/1 12:01',
        status: {
            text: "随便写点什么都能显示"
        }

    },
    {
        name: '小李',
        field: '1',
        startTime: '2018/1/1 16:00',
        endTime: '2018/1/1 17:00',
        status: {
            text: "已订购"
        }
    },
    {
        name: '呵呵',
        field: '5',
        startTime: '2018/1/1 8:30',
        endTime: '2018/1/1 12:30',
        style: {
            background: "-webkit-linear-gradient(left, red, blue)"
        },
        status: {
            text: "已订购"
        },
        bespoke: "颜色可以自定义"
    }
];

// 场馆场地数据
var venueInfo = {
    kaiguanTime: '2018/1/1 8:00',
    biguanTime: '2018/1/1 20:00',
    venue: [
        {
            name: '一号场馆'
        },
        {
            name: '二号场馆'
        },
        {
            name: '三号场馆'
        },
        {
            name: '四号场馆'
        },
        {
            name: '五号场馆'
        }
    ]
};
// 中英文翻译，用于悬浮窗提示信息
var o = {
    "name": "姓名",
    "field": "场馆",
    "startTime": "开始时间",
    "endTime": "结束时间",
    "bespoke": "订购状态"
};

var table = $('#table'),
    rows = $('#rows'),
    head = $('#head');

var kaiguanTime = new Date('2018/1/1 8:00'),    //开馆时间
    biguanTime = new Date('2018/1/1 20:00');    //闭馆时间
var kaiguanHours = kaiguanTime.getHours(),
    biguanHours = biguanTime.getHours();
var businessHours = biguanHours - kaiguanHours;   //营业小时数。闭馆的小时减去开馆的小时，就是营业的小时数，为方便画出表格。不精确到分
var venue = venueInfo.venue,
    venueNum = venue.length;

// 根据场馆数据绘制表格--开始
var arr = [];       //将8点到20点。利用数组的下标0、1、2、3确定是periodCell中的哪个格子
var ul = '',
    headLi = '';

for (var x = 0; x < venueNum; x++) {
    ul += '<ul class="row">';
    for (var i = 0; i <= businessHours; i++) {
        if (x == 0) {
            arr.push(kaiguanHours);
            headLi += '<li><span>' + kaiguanHours + ':00</span></li>';
            kaiguanHours++;
        }
        if (i == 0) {
            ul += '<li class="venueName">' + venue[x].name + '</li>';
            continue;
        }
        ul += '<li class="periodCell"></li>';
    }
    ul += '</ul>';
}
head.html(headLi);
rows.html(ul);
// 根据场馆数据绘制表格--结束


var periodCell = $('.periodCell');      //表格中的单元格


// drawCell(datas);


window.onresize = function () {
    // drawCell(datas);
    drawCell(storage.get("datas"));
};


/**
 * 根据场馆、开始时间、结束时间在表格中画出用户选择的时间段
 * @param field     场地，编号从1开始
 * @param startTime     预定开始时间
 * @param endTime   预定结束时间
 */
function drawCell(data) {
    if (data == null) {
        return;
    }
    // $('.sel').remove();
    /*
     var thatData = JSON.stringify(data);
     thatData = JSON.parse(thatData);
    */
    var thatData = data.slice();    //复制数组,避免修改数组导致元数据被修改
    var periodWidth = periodCell.outerWidth();     //每一个单元格宽度
    var tenMinutesWidth = periodWidth / 6;      //10分钟一格格子宽度

    thatData.forEach(function (value) {
        var status = "";

        try {
            status = value.status.text;
        } catch (e) {
            status = "";
        }

        var style = value.style;
        delete value.style;
        delete value.status;
        var info = JSON.stringify(value);


        var field = value.field,
            startTime = value.startTime,
            endTime = value.endTime;

        var startTimeObj = new Date(startTime),
            endTimeObj = new Date(endTime);
        var startHours = startTimeObj.getHours();
        var cellNum = (endTimeObj - startTimeObj) / 1000 / 60 / 10;        //用户订购场地的时长占多少个10分钟一格的格子
        var width = tenMinutesWidth * cellNum;      //10分钟一格格子个数乘10分钟一格格子宽度
        var leftNum = startTimeObj.getMinutes() / 10;      //开始分钟数占10分钟一格格子的个数
        var left = leftNum * tenMinutesWidth;       //开始分钟乘10分钟一格格子宽度

        var sel = $("<div" + " class='sel' info='" + info + "'>" + "<span class='selMes'>" + status + "</span>" + "</div>").css($.extend({
            width: width,
            left: left
        }, style));
        var index = (field - 1) * businessHours + arr.indexOf(startHours);
        periodCell.eq(index).html(sel);

        bindHover();
    });

    $('.sel').off('contextmenu');   //防止多次调用drawCell方法时给元素重复绑定右键菜单事件
    var contextmenu = $('#contextmenu');
    $('.sel').on('contextmenu', function (e) {
        e = $.event.fix(e);
        e.preventDefault();
        var x = e.pageX,
            y = e.pageY;
        contextmenu.css({
            left: x + 2,
            top: y + 2,
            zIndex: 1,
            visibility: 'visible'
        });
    });
}


function bindHover() {
    var hoverMessage = $('#hoverMessage'),
        message = $('#message'),
        sel = $('.sel');
    sel.mouseover(function (e) {
        var $this = $(this);
        var $hoverObj = $(e.target);
        if (!($hoverObj.attr('class') == 'sel' ? true : $hoverObj.attr('class') == 'selMes' ? true : false)) {
            return;
        }
        var info = $.parseJSON($this.attr('info'));

        var li = "";
        for (i in info) {
            if (!o[i]) {
                continue;
            }
            li += "<li>" + o[i] + "：" + info[i] + "</li>";
        }
        message.html(li);

        var $mesWidth = hoverMessage[0].offsetWidth / 2,
            $mesHeight = hoverMessage[0].offsetHeight + 13,
            $thisWidth = $this[0].offsetWidth / 2,
            $thisOffsetLeft = $this.offset().left,
            $thisOffsetTop = $this.offset().top;
        var $offsetX = $thisWidth - $mesWidth;
        var x = $thisOffsetLeft + $offsetX,
            y = $thisOffsetTop - $mesHeight;
        hoverMessage.css({
            "left": x,
            "top": y,
            "opacity": 1,
            "visibility": "visible"
        });
    });

    sel.mouseout(function (e) {
        if (e.target.className == 'sel' ? e.relatedTarget.className == 'selMes' : e.target.className == 'selMes' ? true : false) {
            return;
        }
        hoverMessage.css({
            "visibility": "hidden",
            "opacity": 0
        });
    });
}


var username = $('#name'),
    userfield = $('#field'),
    userStartTime = $('#startTime'),
    userEndTime = $('#endTime'),
    userCustomize = $('#customize');
bt = $('#bt');

var usernameValue, userfieldValue, userStartTimeValue, userEndTimeValue;
var timeTips = $('#timeTips');
var fieldOption = '<option value="">请选择场馆</option>';
for (var i = 1; i < 6; i++) {
    fieldOption += "<option value='" + i + "' " + (i == 1 ? "selected" : "") + ">" + i + "</option>";
}
userfield.html(fieldOption);

var tips = $('.tips');
bt.on('click', function () {
    usernameValue = username.val();
    userfieldValue = userfield.find('option:selected').val();
    userStartTimeValue = userStartTime.val();
    userEndTimeValue = userEndTime.val();
    customizeValue = userCustomize.val();

    var verify = [
        {
            "RegExp": /^[\u4e00-\u9fa5]{2,4}$/,
            "RegObj": usernameValue,
            "errMes": "用户名不正确啊",
            "thisObj": username
        },
        {
            "RegExp": /\d/,
            "RegObj": userfieldValue,
            "errMes": "没有选择场馆",
            "thisObj": userfield
        },
        {
            "RegExp": /^([01][0-9]|2[0-3]):([0-5][0-9])$/,
            "RegObj": userStartTimeValue,
            "errMes": "开始时间输入格式不对",
            "thisObj": userStartTime
        },
        {
            "RegExp": /^([01][0-9]|2[0-3]):([0-5][0-9])$/,
            "RegObj": userEndTimeValue,
            "errMes": "结束时间输入格式不对",
            "thisObj": userEndTime
        }
    ];
    var flag = 0;
    $.each(verify, function (i) {
        if (!verify[i].RegExp.test(verify[i].RegObj)) {
            tips.eq(verify[i].thisObj.parent().index()).text(verify[i].errMes).css({
                "color": "red"
            });
        } else {
            tips.eq(verify[i].thisObj.parent().index()).text("");
            flag++;
        }
    });
    if (flag == tips.length) {
        var oldDatas = storage.get("datas");
        for (var i = 0, length = oldDatas.length; i < length; i++) {
            var startTime = new Date(oldDatas[i].startTime),
                endTime = new Date(oldDatas[i].endTime),
                field = oldDatas[i].field;
            var userInputStartTime = new Date('2018/1/1 ' + userStartTimeValue),
                userInputEndTime = new Date('2018/1/1 ' + userEndTimeValue);
            var fieldConflict = field == userfieldValue ? true : false;
            if (fieldConflict) {
                var timeConflict = userInputStartTime > endTime || userInputEndTime < startTime ? false : true;
                if (timeConflict) {
                    timeTips.text('场馆选择时间有冲突!!虽然这个提示的位置是在结束时间这里。但是我要说的是时间段有冲突，而不仅仅代表结束时间有冲突').css({
                        "color": "red"
                    });
                    return;
                } else {
                    timeTips.empty();
                }
            }
        }


        var datas = [{
            name: usernameValue,
            field: userfieldValue,
            startTime: '2018/1/1 ' + userStartTimeValue,
            endTime: '2018/1/1 ' + userEndTimeValue,
            style: {
                // background: "red"
            },
            status: {
                text: customizeValue ? customizeValue : "已被预订"
            },
            bespoke: "预定成功"
        }];
        storage.set('datas' + (storage.getNum() + 1), datas);
        drawCell(datas);
    }
});

var storage = {
    set: function (key, value) {
        window.localStorage.setItem(key, JSON.stringify(value[0]));
    },
    get: function (key) {
        var arr = [];
        var num = storage.getNum()
        for (var i = 1; i <= num; i++) {
            arr.push(JSON.parse(window.localStorage.getItem(key + i)));
        }
        return arr;
    },
    getNum: function () {
        var arr = [];
        for (var key in window.localStorage) {
            if (key.match(/datas/) == 'datas') {
                arr.push(key.match(/\d*$/)[0]);
            }
        }
        return arr.length ? Math.max.apply(null, arr) : 0;
    }
}


// drawCell(storage.get("datas"));
drawCell(datas);


